package com.scalar.chiptrack.adaptor.chartered;

import com.scalar.ScalarException;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.dao.FabSortAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: ChandraSekhar
 * Date: Aug 30, 2006
 * Time: 1:48:30 AM
 */
public class CharteredDataParser extends JobHandler implements AdaptorConstants
{
       private static Logger m_parserLogger     = null;
       private String m_dataOutputDir           = null;

       private HashMap<String, FabSortLot> m_WipStatusMap   = new HashMap<String, FabSortLot>();
       private HashMap<String, ShippedLot> m_ShipStatusMap  = new HashMap<String, ShippedLot>();
       DBTransaction dbTransaction              = null;

       public CharteredDataParser() throws ScalarException
       {
           try
           {
               m_dataOutputDir = AdaptorUtils.getDataOutputDir(VENDOR_NAME_CHARTERED, WIP_TYPE_FAB);
               AdaptorUtils.makeAllAdaptorDirs(m_dataOutputDir);
               m_parserLogger = AdaptorUtils.getDataParserLogger(m_dataOutputDir, VENDOR_NAME_CHARTERED);
               FabSortAdaptorDAO.setLogger(m_parserLogger);
               ShippedLotDAO.setLogger(m_parserLogger);
               AdaptorUtils.setLogger( m_parserLogger);
           }
           catch ( ScalarException se )
           {
               log( "ERROR!! ERROR!! ERROR!! Exception while loading CHARTERED WIP Status output directory details from database, Exception: " + se );
               throw se;
           }
       }

       public static void main( String args[] ) throws Exception
       {
           new CharteredDataParser().execute();
       }


       public void execute() throws Exception
       {

           AdaptorUtils.printHeader(VENDOR_NAME_CHARTERED, CONSTANT_PARSER);

           File doneDestDir = new File( m_dataOutputDir + "/done");

           File wipDataoutDir = new File( m_dataOutputDir );

           File[] fileList = wipDataoutDir.listFiles();

           if ( ( fileList == null ) || ( fileList.length <= 3 ) )
           {
               log( "No file found in directory: " + wipDataoutDir );
               throw new ScalarException( "No file found in directory: " + wipDataoutDir + "----\n\n" );
           }

           ArrayList<File> successFileList    = new ArrayList<File>();
           boolean success              = true;

           //PARSING STARTS FROM HERE
           for ( int i = 0; i < fileList.length; i++ )
           {

               if ( fileList[i].isDirectory() == true )
               {
                   continue;
               }

               if ( ( fileList[i].getName() != null ) && ( fileList[i].getName().trim().startsWith ( CharteredAdaptor.FILE_NAME_WIP_STATUS ) ) )
               {
                   try
                   {
                        // Parse the file and get the lot list
                        FileReader reader = new FileReader( fileList[i].getAbsolutePath() );

                        CharteredHtmlWipParser htmlParser = new CharteredHtmlWipParser();

                        //Here the HTML parsing starts
                        ArrayList<CharteredWipStatus> m_wipStatusList = htmlParser.parse( reader );

                        if ( m_wipStatusList != null && m_wipStatusList.size() > 0 )
                        {
                            getWipStatusInfoList( m_wipStatusList );
                        }

                        //Add files to success list to move to /done directory
                        successFileList.add( fileList[i] );

                        try
                        {
                            if ( reader != null)
                            {
                                reader.close();
                                reader = null;
                            }
                        }
                        catch(IOException ignore)
                       {

                       }
                   }
                   catch ( Exception e )
                   {
                       success = false;
                       log( "Exception while parsing and storing file: " + fileList[i].getName() + "\nException: " + e );
                       e.printStackTrace();
                       throw e;
                   }

               }
               if ( ( fileList[i].getName() != null ) && ( fileList[i].getName().trim().startsWith( CharteredAdaptor.FILE_NAME_SHIP_STATUS ) ) )
               {
                   try
                   {      // Parse the file and get the lot list
                        FileReader reader = new FileReader( fileList[i].getAbsolutePath() );

                        CharteredHtmlShipParser htmlParser = new CharteredHtmlShipParser();

                        //Here the HTML parsing starts
                        ArrayList<CharteredShipStatus> m_shipStatusList = htmlParser.parse( reader );

                        if ( m_shipStatusList != null && m_shipStatusList.size() > 0 )
                        {
                            getShipStatusInfoList( m_shipStatusList );
                        }

                        //Add files to success list to move to /done directory
                        successFileList.add( fileList[i] );

                       try
                       {
                           if ( reader != null)
                           {
                               reader.close();
                               reader = null;
                           }
                       }
                       catch(IOException ignore)
                       {

                       }
                   }
                   catch ( Exception e )
                   {
                       success = false;
                       log( "Exception while parsing and storing file: " + fileList[i].getName() + "\nException: " + e );
                       e.printStackTrace();
                       throw e;
                   }
               }
           }


           //to save the wip Status sheet tables
           /*try
           {
               // Step 1
               // Save Fab Wip, dumbping the Sheet information
              if ( m_wipStatusList == null )
              {
                  m_wipStatusList = new ArrayList();
              }
              if ( m_wipStatusList.isEmpty() == false )
               {
                   log( "Updating Fab Lot Information of Sheet" );
                   CharteredDAO.saveCharteredWipDetails( null, m_wipStatusList );
               }

           }
           catch ( Exception e )
           {
               success = false;
               log( "ERROR!! ERROR!! ERROR!! Could not update Fab information into database: " + e );
               e.printStackTrace();
               throw e;
           }*/

           //to save the Chartered Ship sheet tables
           /*try
           {
               // Save Fab Shipment Full sheet information
               if( m_shipStatusList == null )
               {
                   m_shipStatusList = new ArrayList();
               }
               if ( m_shipStatusList.isEmpty() == false )
               {
                   log( "Updating Ship Lot Information of Sheet" );
                   CharteredDAO.saveCharteredShipDetails( null, m_shipStatusList );
               }

           }
           catch ( Exception e )
           {
               success = false;
               log( "ERROR!! ERROR!! ERROR!! Could not update Ship information into database: " + e );
               e.printStackTrace();
               throw e;
           }*/

           // to save the Fab lot tables
           try
           {
               // Save FAB Lot information
               if ( m_WipStatusMap.isEmpty() == false )
               {                      
                   log( "Updating Fab Lot Information" );
                   FabSortAdaptorDAO.saveFabLot( dbTransaction, m_WipStatusMap.values().iterator(), WIP_TYPE_FAB, VENDOR_NAME_CHARTERED );
               }
           }
           catch ( Exception e )
           {
               success = false;
               log( "ERROR!! ERROR!! ERROR!! Could not update Fab Data information into database: " + e );
               e.printStackTrace();
               throw e;
           }

           try
           {
               // Save shipping info
               if ( m_ShipStatusMap.isEmpty() == false )
               {
                   log( "Updating shipment Information" );
                   ShippedLotDAO.saveShippedLot( dbTransaction, m_ShipStatusMap.values().iterator() );
               }
           }
           catch ( Exception e )
           {
               success = false;
               log( "ERROR!! ERROR!! ERROR!! Could not update CHARTERED Shipping information into database: " + e );
               e.printStackTrace();
               throw e;
           }

           // To Close the Drop Out Lots
           AdaptorDAO.closeDropOutLots( VENDOR_NAME_CHARTERED );

           // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
           AdaptorDAO.sendAllNotifications( VENDOR_NAME_CHARTERED, true, true, true );


           int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( CharteredAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

            // Update Adaptor_Run_Info table
            try
            {
                if ( success == true )
                {
                    AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, CharteredAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                    System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
                }
            }
            catch ( ScalarException se )
            {
                success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, CharteredAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
                throw se;
            }

           // Step 7
           // Move the successful files to 'done' directory
           if ( success )
           {
               AdaptorUtils.moveFilesToDone(successFileList, doneDestDir );
           }
       }//end of execute method

       /**
       *
       * @param wipdataList
       */
       public void getWipStatusInfoList( ArrayList wipdataList ) throws ScalarException
       {
           if ( wipdataList == null || wipdataList.size() == 0 )
           {
               return;
           }

           CharteredWipStatus wipStatusReport   = null;
           String partNumber                    = null;
           String lotNumber                     = null;
           FabSortLot fabSortLot                = null;
           try
           {
               Iterator iterator = wipdataList.iterator();
               while ( iterator.hasNext() )
               {
                   wipStatusReport = ( CharteredWipStatus ) iterator.next();

                   if ( wipStatusReport != null )
                   {
                       partNumber = wipStatusReport.getCustomerProduct();
                       lotNumber  = wipStatusReport.getCustomerLot() ;
                       if ( partNumber == null )
                       {
                            partNumber = wipStatusReport.getVendorPartNumber();
                       }
                       if ( lotNumber != null && partNumber != null )
                       {
                           fabSortLot = ( FabSortLot ) m_WipStatusMap.get( partNumber + lotNumber );
                           if ( fabSortLot == null )
                           {
                               fabSortLot = new FabSortLot();
                               m_WipStatusMap.put( partNumber + lotNumber , fabSortLot );
                           }
                           int quantity = 0;
                           if ( fabSortLot.getQtyIn() != null )
                           {
                               try
                               {
                                   quantity = Integer.parseInt ( fabSortLot.getQtyIn() );
                               }
                               catch ( NumberFormatException ignore )
                               {
                               }
                               try
                               {
                                   quantity += Integer.parseInt ( wipStatusReport.getWaferQty() );
                               }
                               catch ( NumberFormatException ignore )
                               {
                               }
                           }
                           else
                           {
                               try
                               {
                                   quantity = Integer.parseInt ( wipStatusReport.getWaferQty() );
                               }
                               catch ( NumberFormatException ignore )
                               {
                               }
                           }

                           String dateIn           = null;
                           String shipFcstDate     = null;
                           String shipConfDate     = null;
                           String expectedDateOut  = null;
                           String outLookDate      = null;

                           if ( wipStatusReport.getDateIn() != null && wipStatusReport.getDateIn().trim().length() > 0 )
                           {
                                  dateIn = StringUtils.formatDate ( wipStatusReport.getDateIn(), "dd-MMM-yy", "MM/dd/yyyy" );
                           }

                           if ( wipStatusReport.getEdoDate() != null &&  wipStatusReport.getEdoDate().trim().length() > 0 )
                           {
                               expectedDateOut = StringUtils.formatDate ( wipStatusReport.getEdoDate(), "dd-MMM-yy", "MM/dd/yyyy" );
                           }

                           if( wipStatusReport.getActFaboutDate() != null && wipStatusReport.getActFaboutDate().trim().length() > 0 )
                           {
                                outLookDate = StringUtils.formatDate ( wipStatusReport.getActFaboutDate(), "dd-MMM-yy", "MM/dd/yyyy" );
                           }

                           if( wipStatusReport.getCommitDate() != null && wipStatusReport.getCommitDate().trim().length() > 0 )
                           {
                                shipFcstDate = StringUtils.formatDate ( wipStatusReport.getCommitDate(), "dd-MMM-yy", "MM/dd/yyyy" );
                           }
                           if( wipStatusReport.getExpectedDateOut() != null && wipStatusReport.getExpectedDateOut().trim().length() > 0 )
                           {
                                shipConfDate = StringUtils.formatDate ( wipStatusReport.getExpectedDateOut(), "dd-MMM-yy", "MM/dd/yyyy" );
                           }

                           if ( quantity > 0 )
                           {
                               fabSortLot.setFabId ( wipStatusReport.getFabGroup());
                               fabSortLot.setFabPartName ( wipStatusReport.getVendorPartNumber() );
                               fabSortLot.setProcessGen ( wipStatusReport.getGeometryname() );
                               fabSortLot.setProcess ( wipStatusReport.getProcessName());
                               fabSortLot.setWsQty ( wipStatusReport.getWaferQty());
                               fabSortLot.setSoNumber ( wipStatusReport.getSoNo() );
                               fabSortLot.setPriorty ( wipStatusReport.getLotPriority());
                               fabSortLot.setLayerPosition ( wipStatusReport.getBalanceMaskNo() );
                               fabSortLot.setShip_fcst_date( shipFcstDate );
                               fabSortLot.setShip_conf_date( shipConfDate );
                               fabSortLot.setFabLotNumber(lotNumber);

                               fabSortLot.setLotId( lotNumber );
                               fabSortLot.setCustProduct( partNumber );
                               fabSortLot.setDateIn( dateIn );
                               fabSortLot.setQtyIn( quantity +"");
                               fabSortLot.setStage( wipStatusReport.getCurrentStage() );
                               fabSortLot.setPoNumber( wipStatusReport.getCustPo());
                               fabSortLot.setStagePosition( wipStatusReport.getStagePosition() );
                               fabSortLot.setForcastedDateOut( expectedDateOut );
                               fabSortLot.setOutLookDate( outLookDate );
                               fabSortLot.setVendorName( VENDOR_NAME_CHARTERED );
                               fabSortLot.setWaferID( wipStatusReport.getWaferID() );
                               fabSortLot.setPsType(WIP_TYPE_FAB);
                               fabSortLot.setLotCategory ( LOT_CATEGORY_TYPE_PROD );
                               if ( "HELD".equalsIgnoreCase ( wipStatusReport.getLotState() ) )
                               {
                                    fabSortLot.setLotStatus ( LOT_STATUS_HOLD );
                               }
                               else
                               {
                                    fabSortLot.setLotStatus ( LOT_STATUS_RUNNING );
                               }
                           }
                       }
                   }
               }
           }
           catch(Exception e )
           {
             log( "ERROR!!! ERROR!!! While Parsing the Chartered Fab Data" + e);
             e.printStackTrace();
             throw new ScalarException("ERROR!!! ERROR!!! While Parsing the Chartered Fab Data" + e );
           }
        }

        /**
       *
       * @param shipdataList
       */
       public void getShipStatusInfoList ( ArrayList shipdataList ) throws ScalarException
       {
           if ( shipdataList == null || shipdataList.size() == 0 )
           {
               return;
           }
           CharteredShipStatus shipStatusReport = null;
           String partNumber                    = null;
           String lotNumber                     = null;
           ShippedLot shippedLot                = null;

           try
           {
               Iterator iterator = shipdataList.iterator();
               while ( iterator.hasNext() )
               {
                   shipStatusReport = ( CharteredShipStatus ) iterator.next();

                   if ( shipStatusReport != null )
                   {
                       partNumber = shipStatusReport.getCustPartNo();
                       lotNumber  = shipStatusReport.getCustomerLot();
                       String shipDate = null;
                       if ( shipStatusReport.getShipDate() != null && shipStatusReport.getShipDate().trim().length() > 0 )
                       {
                           shipDate =  StringUtils.formatDate( shipStatusReport.getShipDate(), "dd-MMM-yy", "MM/dd/yyyy" );
                       }
                       if ( partNumber == null )
                       {
                            partNumber = shipStatusReport.getVendorPartNo();
                       }
                       if ( lotNumber != null && partNumber != null )
                       {
                           shippedLot = ( ShippedLot ) m_ShipStatusMap.get( partNumber + lotNumber + shipDate + shipStatusReport.getShipToLocation() + shipStatusReport.getCustPo() );
                           if ( shippedLot == null )
                           {
                               shippedLot = new ShippedLot();
                               m_ShipStatusMap.put( partNumber + lotNumber + shipDate +shipStatusReport.getShipToLocation()+ shipStatusReport.getCustPo() , shippedLot );
                           }
                           int quantity = 0;
                           if ( shippedLot.getShipQty() != null )
                           {
                               try
                               {
                                   quantity = Integer.parseInt ( shippedLot.getShipQty() );
                               }
                               catch ( NumberFormatException ignore )
                               {
                               }
                               try
                               {
                                   quantity += Integer.parseInt ( shipStatusReport.getShipWaferQty() );
                               }
                               catch ( NumberFormatException ignore )
                               {
                               }
                           }
                           else
                           {
                               try
                               {
                                   quantity = Integer.parseInt ( shipStatusReport.getShipWaferQty() );
                               }
                               catch ( NumberFormatException ignore )
                               {
                               }
                           }
                           if ( quantity > 0 )
                           {
                               shippedLot.setPartNumber( partNumber);
                               shippedLot.setLotNumber( lotNumber );
                               shippedLot.setFabLotNumber( lotNumber );
                               shippedLot.setShipDate (  shipDate );
                               shippedLot.setShipQty ( quantity +"" );
                               shippedLot.setInvoiceNumber ( shipStatusReport.getInvoiceNo() );
                               shippedLot.setCurrentLocation ( LOCATION_TYPE_FAB );
                               shippedLot.setCustomerPO ( shipStatusReport.getCustPo() );

                               if ( shipStatusReport.getShipToLocation() != null && (shipStatusReport.getShipToLocation().indexOf("Orient Semi") != -1 || shipStatusReport.getShipToLocation().indexOf("OSE") != -1 ) )
                               {
                                   shippedLot.setNextLocation ( VENDOR_NAME_OSEP );
                               }
                               else if (shipStatusReport.getShipToLocation() != null && shipStatusReport.getShipToLocation().indexOf("Mitsui") != -1  )
                               {
                                   shippedLot.setNextLocation ( VENDOR_NAME_MITSUI );
                               }
                               else
                               {
                                   shippedLot.setNextLocation (shipStatusReport.getShipToLocation() );
                               }
                               shippedLot.setVendorName ( VENDOR_NAME_CHARTERED );
                               shippedLot.setWaferID ( shipStatusReport.getWaferID() );
                               shippedLot.setEta ( shipStatusReport.getEtaDate() );
                               shippedLot.setEtd ( shipStatusReport.getEtdDate() );
                               shippedLot.setFlightNumber ( shipStatusReport.getFlightNo() );
                               shippedLot.setHawb( shipStatusReport.getHawbNo());
                               shippedLot.setMawb( shipStatusReport.getMawbNo() );
                           }
                       }
                   }
               }
           }
           catch( Exception e)
           {
               log ("ERROR!!! ERROR!! While parsing the Chartered Data to Shipped Lot" + e);
               e.printStackTrace();
               throw new ScalarException ("ERROR!!! ERROR!! While parsing the Chartered Data to Shipped Lot" + e);
           }
        }

       /**
        *
        * @param message
        */
       private static void log( String message )
       {

           if ( message == null ) return;

           if ( m_parserLogger != null )
           {
               synchronized ( m_parserLogger )
               {
                   m_parserLogger.logDebug ( message + LINE_SEPARATOR );
               }
           }
           else
           {
               System.out.println ( message );
           }
       }
}
